package by.pavlyukevich.paymentsystem.dataaccess.user.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.pavlyukevich.paymentsystem.dataaccess.filter.Filter;
import by.pavlyukevich.paymentsystem.dataaccess.filter.UserAccountFilter;
import by.pavlyukevich.paymentsystem.dataaccess.impl.AbstractDaoImpl;
import by.pavlyukevich.paymentsystem.dataaccess.user.UserAccountDao;
import by.pavlyukevich.paymentsystem.datamodel.user.UserAccount;
import by.pavlyukevich.paymentsystem.datamodel.user.UserAccount_;

@Repository
public class UserAccountDaoImpl extends AbstractDaoImpl<Integer, UserAccount> implements
		UserAccountDao {

	protected UserAccountDaoImpl() {
		super(UserAccount.class);
	}

	@Override
	public List<UserAccount> getList(Filter<UserAccount> userAccountFilter) {

		CriteriaQuery<UserAccount> criteria = getAllCriteria(userAccountFilter);

		addCriteriaRestrict(criteria, userAccountFilter);

		Root<UserAccount> root = getRoot(criteria, UserAccount.class);
		root.fetch(UserAccount_.individual, JoinType.LEFT);
		root.fetch(UserAccount_.contractor, JoinType.LEFT);

		return getList(criteria, userAccountFilter);
	}

	@Override
	public long getCount(Filter<UserAccount> userAccountFilter) {
		CriteriaQuery<Long> criteria = getCountAllCriteria();
		addCriteriaRestrict(criteria, userAccountFilter);
		return getSingle(criteria);
	}

	private <T> CriteriaQuery<T> addCriteriaRestrict(CriteriaQuery<T> criteria,
			Filter<UserAccount> filter) {
		if (filter == null) {
			return criteria;
		}
		Root<UserAccount> root = getRoot(criteria, UserAccount.class);
		CriteriaBuilder cBuilder = getEntityManager().getCriteriaBuilder();
		List<Predicate> predicateList = new ArrayList<Predicate>();
		UserAccountFilter userAccountFilter = (UserAccountFilter) filter;
		if (userAccountFilter.getLogin() != null) {
			predicateList.add(cBuilder.equal(root.get(UserAccount_.login),
					userAccountFilter.getLogin()));
		}
		if (userAccountFilter.getPassword() != null) {
			predicateList.add(cBuilder.equal(root.get(UserAccount_.password),
					userAccountFilter.getPassword()));
		}
		if (userAccountFilter.getIndividual() != null) {
			predicateList.add(cBuilder.equal(root.get(UserAccount_.individual),
					userAccountFilter.getIndividual()));
		}
		if (userAccountFilter.getContractor() != null) {
			predicateList.add(cBuilder.equal(root.get(UserAccount_.contractor),
					userAccountFilter.getContractor()));
		}
		if (predicateList.size() > 0) {
			Predicate predicateArray[] = predicateList.toArray(new Predicate[0]);
			criteria.where(predicateArray);
		}

		return criteria;
	}

}
